package com.cloudpivot.project.rabbitmq.service;

import com.rabbitmq.client.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class ProducerService {
    @Value("${rabbitmq-config.host-name}")
    private String HOST_NAME;
    @Value("${rabbitmq-config.host-port}")
    private Integer HOST_PORT;
    @Value("${rabbitmq-config.username}")
    private String USER_NAME;
    @Value("${rabbitmq-config.password}")
    private String PASSWORD;
    private static final String QUEUE_NAME = "first_queues";
    private static final String EXCHANGE_NAME = "amq.direct";
    private static final String VIRTUAL_HOST = "/test";

    public void sendToRabbitMQ(String message)throws Exception {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost(HOST_NAME);
        factory.setPort(HOST_PORT);
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        factory.setVirtualHost(VIRTUAL_HOST);
        Connection rabbitMQConnection= factory.newConnection();
        Channel channel = rabbitMQConnection.createChannel();
        Map<String, Object> params = new HashMap<>();
        //绑定交换机
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT, true, false, params);
        //绑定队列
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        //队列与交换机绑定
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME,"key1");
        channel.basicPublish(EXCHANGE_NAME,"key1", MessageProperties.TEXT_PLAIN,message.getBytes("UTF-8"));
        channel.close();
        rabbitMQConnection.close();
    }

    public void sendToRabbitMQHas(String message,String routingKey)throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST_NAME);
        factory.setPort(HOST_PORT);
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        factory.setHost(HOST_NAME);
        factory.setVirtualHost(VIRTUAL_HOST);
        String exchange_name = "amq.direct";
        Connection rabbitMQConnection= factory.newConnection();
        Channel channel = rabbitMQConnection.createChannel();
        channel.exchangeDeclare(exchange_name, BuiltinExchangeType.DIRECT, true, false, new HashMap<>());
        channel.basicPublish(exchange_name,routingKey,MessageProperties.TEXT_PLAIN,message.getBytes("UTF-8"));
        channel.close();
        rabbitMQConnection.close();
    }


}
